//
//  ComplaintVC.m
//  NtoccShipper
//
//  Created by mac on 2019/12/17.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "ComplaintVC.h"
#import "HDPicModle.h"
#import "GetPhoto.h"
#import "CJDateTime.h"
#import "XLImageViewer.h"
#import "UpLoadImageCell.h"
#import "UploadImgModel.h"
#import <AMapLocationKit/AMapLocationKit.h>

static NSString* reuseCellIdentifier = @"UpLoadImageCell";

@interface ComplaintVC ()< AMapLocationManagerDelegate,UICollectionViewDelegate,
UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) CJTextField *fieldComplaintTime;
@property (nonatomic,strong) CJTextField *fieldComplaintExplain; // 说明
@property (nonatomic,strong) CJTextField *fieldComplaintReson; // 原因
@property (nonatomic,copy) NSString *strComplaintResonCode;

//@property (nonatomic,assign) BOOL isChangeReturnOrderImg; // 是否更改
//@property (nonatomic,strong) NSMutableArray *arrCommentImgs;
@property (nonatomic,strong) CJLabel *labReturnOrderImgIndex;

@property (nonatomic,strong) AMapLocationManager *locationManager;
@property (nonatomic,copy) NSString *strLatitudeMap; // 地图获取过来的
@property (nonatomic,copy) NSString *strLongitudeMap;
@property (nonatomic,copy) NSString *strAddress;
@property (nonatomic,strong) FlexTouchView *touchViewAddImg;

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *arrModel;
@property (nonatomic,strong) CJButton *btnSave;

@end

@implementation ComplaintVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:CJLString(@"投诉")];
    [self setBackLeftButton:@""];
    self.view.backgroundColor = [UIColor cjWhiteColor];

//    self.arrCommentImgs = [[NSMutableArray alloc]init];
    self.strComplaintResonCode = @"";
    self.strLatitudeMap = @""; // 地图获取过来的
    self.strLongitudeMap = @"";
    self.strAddress = @"";
    
    self.arrModel = [[NSMutableArray alloc]init];
    for (int i = 0; i < 1; i++) {
        UploadImgModel *model = [[UploadImgModel alloc]init];
        model.strImgUrl = @"";
        model.strTitle = @"";
        model.changeImg = NO;
        model.hideDeleteImg = YES;
        [self.arrModel addObject:model];
    }
    
    [self createCollection];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self initLocationManager];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)btnSelectUnloadGoodsAction{
    
    WS(ws);
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]initWithPickerMode:BRDatePickerModeYMDHM];
    datePickerView.title =  @"请选择时间 ";
    datePickerView.minDate = [NSDate br_setYear:2016 month:5 day:1];
    datePickerView.maxDate = [NSDate date];  //[NSDate br_setYear:2050 month:5 day:1];
    datePickerView.resultBlock = ^(NSString *selectValue) {

        ws.fieldComplaintTime.text = selectValue;
    };
    
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    datePickerView.pickerStyle = customStyle;
    [datePickerView show];

}

- (void)btnTouchTouSuYuanYinAction{
    [self btnSelectGoodTypeDicts:CJAbnormalType];
}

- (void)btnSelectGoodTypeDicts:(CJGetSendGoodsType )type{
    [self.view endEditing:YES];
    WS(ws);
    [CJNetWork getSenGoodsDicsTypeinfo:type Success:^(id  _Nullable responseObject) {
        
        DLog(@"====== %@",responseObject);
//        [ws btnSelectTypeAction];
        NSDictionary *dic = responseObject[0];
        NSMutableArray *arrMutar = [[NSMutableArray alloc]init];
        NSMutableArray *arrMutarCodes = [[NSMutableArray alloc]init];

        [dic[@"dictList"] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [arrMutar addObject:obj[@"name"]];
            [arrMutarCodes addObject:obj[@"code"]];
            DLog(@"===== %@",arrMutarCodes);
            
        }];

        [ws btnSelectType:type list:arrMutar listCodes:arrMutarCodes title:dic[@"name"]];
        
    }];
    
}

- (void)btnSelectType:(CJGetSendGoodsType )type list:(NSArray *)list listCodes:(NSMutableArray *)arryCodes title:(NSString *)strTitle{
    
    [self.view endEditing:NO];
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]initWithPickerMode:BRStringPickerComponentSingle];
    stringPickerView.title = strTitle;
    stringPickerView.dataSourceArr = list;
    WS(ws);
    stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {

        ws.strComplaintResonCode = arryCodes[resultModel.index];
        ws.fieldComplaintReson.text = resultModel.selectValue;
    };
    
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}

#pragma mark ----------提交数据
- (void)btnSaveInfoAction{
//    [CJAlert showStringDismissWithDelay:@"隐私协议"];
    
    if ([self.strComplaintResonCode isEqualToString:@""]) {
        [CJAlert showStringDismissWithDelay:@"请选择投诉原因"];

    }else if ([CJRegular getIsStrEmpty:self.fieldComplaintExplain.text]) {
        [[[AFViewShaker alloc] initWithView:self.fieldComplaintExplain] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:@"请填写投诉说明"];
            
        }];
    }else if ([CJRegular getIsStrEmpty:self.fieldComplaintTime.text]) {
        [[[AFViewShaker alloc] initWithView:self.fieldComplaintTime] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:@"请选择时间"];
            
        }];
    }else{
        
       __block NSString *strImgs = @"";
        
        if ([self getArrImgsWitHArrModel:self.arrModel] > 0) {
            
            [[self getArrImgsWitHArrModel:self.arrModel] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                if (idx == 0) {
                    strImgs = obj;
                }else{
                    strImgs = CJStringWithFormat(@"%@,%@",strImgs,obj);
                }
                
            }];
        }
        
        NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/orderDetailAbnormal",CJBaseUrl);
        
        NSDictionary *dicPra = @{@"orderDetailCode":self.strCode,
                                 @"abnormalImage":strImgs,
                                 @"abnormalRemark":self.fieldComplaintExplain.text,
                                 @"longitude":self.strLongitudeMap,
                                 @"latitude":self.strLatitudeMap,
                                 @"address":self.strAddress,
                                 @"occurrenceTime":self.fieldComplaintTime.text,
                                 @"abnormalType":[CJControl getThreeUnaryValueStr:self.strComplaintResonCode],
                                 @"abnormalTypeName":[CJControl getThreeUnaryValueStr:self.fieldComplaintExplain.text]
        };
        
        DLog(@"===== %@",dicPra);
        WS(ws);
        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strUrl parameters:dicPra status:OperationTip success:^(id  _Nonnull responseObject) {
            
            if (ws.blockSuccess) {
                ws.blockSuccess(@"");
            }
            [ws pop];
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
    }
}


#pragma mark ----------collectionView
/// 创建tableview 等
- (void)createCollection{
    //    WS(ws);
    CGRect rcFrame = CGRectMake(0, kTopHeight, [[UIScreen mainScreen] bounds].size.width, 0);
    FlexFrameView *header = [[FlexFrameView alloc] initWithFlex:@"ComplaintHeaderView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;

    self.fieldComplaintTime.text = [CJDateTime getCurrentTimesType:CJDateTimeModeYMDHM];

    [header layoutIfNeeded];
    [self.view addSubview:header];
    [self.view addSubview:self.collectionView];

    self.collectionView.frame = CGRectMake(10, kTopHeight + header.height, kScreenWidth -20, kScreenHeight - kTopHeight - header.height -50);
    [self.view addSubview:self.btnSave];
    [self.collectionView reloadData];

}


#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (self.arrModel.count >= 10) {
        return 9;
    }else{
        return self.arrModel.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UpLoadImageCell *cell = (UpLoadImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseCellIdentifier forIndexPath:indexPath];
    
    UploadImgModel *model = self.arrModel[indexPath.row];
    [cell setCellWithModel:model index:indexPath.row arrSum:self.arrModel.count];
    WS(ws);
    cell.blockDelete = ^(id anyObject) {
        [ws btnActionDelecteImgWithIndex:indexPath];
    };
    return cell;
}

- (void)btnActionDelecteImgWithIndex:(NSIndexPath *)indexPath{
    
//    // 如果删除前是2个
//    if (indexPath.row <= 1) {
//        UploadImgModel *model = self.arrModel[indexPath.row];
//        model.strImgUrl = @"";
//        model.hideDeleteImg = YES;
//        [self.arrModel replaceObjectAtIndex:indexPath.row withObject:model];
//    }else{
        [self.arrModel removeObjectAtIndex:indexPath.row];
//    }
    [self.collectionView reloadData];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSLog(@"selected: %d",(int)indexPath.row);
    UploadImgModel *modInfo = self.arrModel[indexPath.row];
    
    if (modInfo.changeImg && ![modInfo.strImgUrl isEqualToString:@""]) {
        [self selelctChangeImgVOrSeeBigPicWitnIndex:indexPath.row isLast:NO];
    }else{

        if (self.arrModel.count == 10) {
            DLog(@"========")
            [CJAlert showStringDismissWithDelay:@"最多只能上传9张图片"];
            return;
        }
        if (indexPath.row + 1 == self.arrModel.count) {
            UploadImgModel *model = [[UploadImgModel alloc]init];

            model.changeImg = NO;
            [self.arrModel addObject:model];
            DLog(@"===== 点击最后一个");
        }
        [self btnUploadImgVWitnIndex:indexPath.row isLast:NO];

    }
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(80, 80);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 20;
}

//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 15;
}

#pragma mark ----------上传图片相关
- (void)selelctChangeImgVOrSeeBigPicWitnIndex:(NSInteger )index isLast:(BOOL)isLast{
    
    WS(ws);
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *change = [UIAlertAction actionWithTitle:@"更换照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [ws uploadImgV];
        [ws btnUploadImgVWitnIndex:index isLast:isLast];
    }];
    UIAlertAction *seeBig = [UIAlertAction actionWithTitle:@"查看大图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[XLImageViewer shareInstanse] showNetImages:[ws getArrImgsWitHArrModel:self.arrModel] index:index fromImageContainer:ws.view];
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertVC dismissViewControllerAnimated:NO completion:^{
    
        }];
    }];

    [alertVC addAction:change];
    [alertVC addAction:seeBig];
    [alertVC addAction:cancle];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

// 上传图片
- (void)btnUploadImgVWitnIndex:(NSInteger )index isLast:(BOOL)isLast{
    
    WS(ws);
    [GetPhoto getPhoto:self completion:^(UIImage *curImage, NSData *imageData) {

        [ws upLoadReturnImageUImage:curImage withNSData:imageData withIndex:index isLast:isLast];
    }];
}

- (void)upLoadReturnImageUImage:(UIImage *)img withNSData:(NSData *)imageData withIndex:(NSInteger )index isLast:(BOOL)isLast{

    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/fileUpload",CJBaseUrl);
    NSURL *str = [[NSURL alloc]initFileURLWithPath:[CJControl getImgFilePath:img]];
    NSDictionary *dic = @{
                          @"file":str
                          };
    HDPicModle *model = [[HDPicModle alloc]init];
    model.pic = img;
    model.picData = imageData;
    model.picName = @"file";
    model.fileName = [CJControl getImgFilePath:img];

    WS(ws);
    [[HDNetworking sharedHDNetworking] POST:strURL parameters:dic andPic:model progress:^(NSProgress * _Nullable progress) {
//        DLog(@"%lf", 1.0 * progress.completedUnitCount / progress.totalUnitCount);
    } success:^(id  _Nonnull responseObject) {

        NSString *strStatus = CJStringWithFormat(@"%@",responseObject[@"status"]);
        NSString *strImgVUrl = [CJControl getThreeUnaryValueStr:responseObject[@"data"]];

        if (strStatus.integerValue == 0) {
            UploadImgModel *model = ws.arrModel[index];
            model.strImgUrl = strImgVUrl;
            model.changeImg = YES;
            model.hideDeleteImg = NO;
            [ws.arrModel replaceObjectAtIndex:index withObject:model];

        }

        [self.collectionView reloadData];

    } failure:^(NSError * _Nonnull error) {
        DLog(@"+++++++%@",error);
    }];
    
}

- (NSMutableArray *)getArrImgsWitHArrModel:(NSMutableArray *)arr{
    
    NSMutableArray *arrImgs = [[NSMutableArray alloc]init];
    NSUInteger y ;
    
    if (arr.count >9) {
        y = 9;
    }else{
        y = arr.count;
    }
    
    for (int i = 0; i < y; i++) {
        
        UploadImgModel *model = arr[i];
        if ([CJControl getIsEmpty:model.strImgUrl]) {
        }else{
            [arrImgs addObject:[CJControl getThreeUnaryValueStr:model.strImgUrl]];
        }
    }
    
    return arrImgs;
}

#pragma mark ----------地图相关-----
- (void)initLocationManager{
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    //设置定位最小更新距离方法
    self.locationManager.distanceFilter = 200;
    //指定单次定位超时时间
    self.locationManager.locationTimeout = 20;

    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:20];
    //持续定位是否返回逆地理信息，默认NO
    self.locationManager.locatingWithReGeocode = YES;
    //开启持续定位
    [self.locationManager startUpdatingLocation];
    
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode{
    
    DLog(@"location:{lat:%f; lon:%f;} and name is %@", location.coordinate.latitude, location.coordinate.longitude,reGeocode.POIName);
    
    if (IsNilOrNull(reGeocode.POIName)) {

    }else{

        self.strLatitudeMap = CJStringWithFormat(@"%f",location.coordinate.latitude);
        self.strLongitudeMap = CJStringWithFormat(@"%f",location.coordinate.longitude);
        self.strAddress = reGeocode.POIName;
        [self.locationManager stopUpdatingLocation];
    }
    
}
- (void)dealloc{
    self.locationManager.delegate = nil;
    [self.locationManager stopUpdatingLocation];
}

#pragma mark ----------lazy
- (UICollectionView *)collectionView{
    
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView =[[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.frame = CGRectMake(10, kTopHeight, kScreenWidth -20, kScreenHeight - kTopHeight);
        [_collectionView registerClass:UpLoadImageCell.class forCellWithReuseIdentifier:reuseCellIdentifier];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor cjWhiteColor];
        
//        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:@"header"];
    }
    return _collectionView;
}

- (CJButton *)btnSave{
    if (!_btnSave) {
        _btnSave = CJButton.btnInit
        .btnFrame(CGRectMake(0,self.collectionView.bottom,kScreenWidth, 50))
        .btnBgColor([UIColor cjMainColor])
        .btnTargetAction(self, @selector(btnSaveInfoAction))
        .btnText(@"确定投诉")
        .btnFont([UIFont cjTitleFont17])
        ;
    }
    return _btnSave;
}

@end

